package cn.clq.ssmshiro.session;

import cn.clq.ssmshiro.util.JedisUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.util.SerializationUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;

/**
 * SessionDAO ,如果我们要把session保存到数据库，就实现自己的SessionDao
 */
public class RedisSessionDao extends AbstractSessionDAO{
    @Resource
    private JedisUtil jedisUtil;
    private static String SESSION_PROFIX = "session_profix:";

    private byte[] getKey(String key){
        return (SESSION_PROFIX+key).getBytes();
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId =generateSessionId(session);
        System.out.println("sessionId++:"+sessionId);
        assignSessionId(session, sessionId); //将sessionid和session绑定
        if(session!=null&&session.getId()!=null){
            byte[] key = getKey(session.getId().toString());
            byte[] value = SerializationUtils.serialize(session);
            jedisUtil.set(key,value);
            jedisUtil.expire(key,600);
        }
        return sessionId;
    }


    @Override
    protected Session doReadSession(Serializable sessionId) {
        System.out.println("doReadSession++");
        byte[] value = jedisUtil.get(getKey(sessionId.toString()));
        return (Session) SerializationUtils.deserialize(value);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {

    }

    @Override
    public void delete(Session session) {
        jedisUtil.del(getKey(session.getId().toString()));
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return null;
    }
}
